<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\model\concern\SoftDelete;

class UserWithdrawModel extends BaseModel
{
    use SoftDelete;

    protected $table='users_withdraw';

    const HANDLE_CANCEL = 'cancel';
    const HANDLE_ACTION = 'action';
    const HANDLE_DEL = 'del';

    protected $step_flow = [
        ['name'=>'待支付','prop_func'=>'fields_status','field'=>'status'],
        ['name'=>'订单已完成','prop_func'=>'fields_status','field'=>'status'],
    ];

    public static $fields_status = [
        ['name'=>'待审核','name_en'=>'Pending review','name_ban'=>'মুলতুবি পর্যালোচনা','color'=>'warning','u_handle'=>[
            self::HANDLE_CANCEL,
        ],'m_handle'=>[
            self::HANDLE_ACTION,
        ]],
        ['name'=>'审核通过','name_en'=>'Passed','name_ban'=>'পরীক্ষায় উত্তীর্ণ','color'=>'success','u_handle'=>[
            self::HANDLE_DEL
        ],'m_handle'=>[ self::HANDLE_DEL ]],
        ['name'=>'审核被拒','name_en'=>'Review rejected','name_ban'=>'পর্যালোচনা বাতিল হয়েছে','color'=>'info','u_handle'=>[self::HANDLE_DEL],'m_handle'=>[self::HANDLE_DEL]],
        ['name'=>'已取消','name_en'=>'Cancelled','name_ban'=>'বাতিল হয়েছে','color'=>'warning','u_handle'=>[
            self::HANDLE_DEL,
        ],'m_handle'=>[
            self::HANDLE_DEL,
        ]],
    ];
    public function getWithdrawInfoAttr()
    {
        return '会员名:'.$this['account_name'].';微信号:'.$this['account'];
    }

    public static function getWithdrawMoney(array $input_data=[])
    {
        $where = [];
        //按月份查询
        $search_month = $input_data['search_month']??'';
        if($search_month){
            $search_start_time = strtotime($search_month);
            $where[] = ['create_time','>=', $search_start_time];
            $where[] = ['create_time','<=',strtotime('+1 month',$search_start_time)];
        }
        if(isset($input_data['uid'])){
            $where[] = ['uid','=',$input_data['uid']];
        }
        $where[] = ['status','=',1]; //审核通过
        return self::where($where)->sum('money');
    }

    public static function getPageData(array $input_data=[])
    {
        $limit = $input_data['limit']??null;
        $activeState = $input_data['activeState']??'';
        $where = [];
        //按月份查询
        $search_month = $input_data['search_month']??'';
        if($search_month){
            $search_start_time = strtotime($search_month);
            $where[] = ['create_time','>=', $search_start_time];
            $where[] = ['create_time','<=',strtotime('+1 month',$search_start_time)];
        }


        $keyword = trim($input_data['keyword']??'');
        !empty($keyword) && $where[] = ['account','like','%'.$keyword.'%'];
        if(isset($input_data['mch_id'])){
            $where[] = ['mch_id','=',$input_data['mch_id']];
        } elseif(isset($input_data['uid'])){
            $where[] = ['uid','=',$input_data['uid']];
        }
        $user_id = $input_data['user_id']??'';
        if(!empty($user_id)){
            $where[] = ['uid','=',$user_id];
        }
        if($activeState=='refuse'){
            $where[] = ['status','=',2];
        }elseif($activeState=='wait'){
            $where[] = ['status','=',0];
        }elseif($activeState=='pass'){
            $where[] = ['status','=',1];
        }elseif($activeState=='cancel'){
            $where[] = ['status','=',3];
        }


        if(isset($input_data['id'])){
            $where[] = ['id','=',$input_data['id']];
        }


        return self::with(['linkUser'])->where($where)->order('id desc')->paginate($limit);
    }

    public static function handleSaveData(UserModel $user_model,array $input_data = [])
    {
        $_lang = $input_data['_lang']??'';
        $mch_id = $input_data['mch_id']??'';
        $name = $input_data['name']??'';
        $account = $input_data['account']??'';
        $money = empty($input_data['money'])?0:(float)$input_data['money'];
        if(empty($name)) throw new \Exception("请输入名称");
        if(empty($account)) throw new \Exception("请输入提现微信号");

        if($money <= 0 ) throw new \Exception("提现金额必须大于:0");
        $withdraw_min_money =  (int)SysSettingModel::getContent('money','withdraw_min_money_int');
        if(empty($withdraw_min_money)) throw new \Exception("提现通道暂已关闭");
        if($withdraw_min_money>$money) throw new \Exception("提现金额必须大于最低额度：".$withdraw_min_money);
        if(!empty($mch_id)){
            $merchant_model = MerchantModel::find($mch_id);
            if(empty($merchant_model)) throw new \Exception("商家信息异常");
            if($merchant_model['money']<$money) throw new \Exception("账户余额不足");

        }else{
            if($user_model['money']<$money) throw new \Exception("账户余额不足");
        }
        //per
        $per = 0;//(float)SysSettingModel::getContent('integral','withdraw_per');
        //创建记录
        try{
            \think\facade\Db::startTrans();
            if(!empty($mch_id)){
                $row_num = MerchantModel::where(['id'=>$mch_id,'money'=>$merchant_model['money']])->update([
                    'money' => \think\facade\Db::raw('money-'.$money),
                ]);
            }else{
                $row_num = UserModel::where(['id'=>$user_model['id'],'money'=>$user_model['money']])->update([
                    'money' => \think\facade\Db::raw('money-'.$money),
                ]);
            }

            if(!$row_num) throw new \Exception("参与人数过多,请稍后尝试");
            $model = new self();
            $service_fee =empty($per)?0: $money*$per;
            $model->setAttrs([
                'uid' => $user_model['id'],
                'mch_id' => $mch_id,
                'money' => $money,
                'account_name' => $name,
                'account' => $account,
                'per' => $per,
                'service_fee' => $service_fee,
                'pay_money' => $money - $service_fee,
                'q_money' => $user_model['money'], //提现钱账户金额
            ]);
//            dump($model->getData());exit;
            $model->save();

            \think\facade\Db::commit();
        }catch (\Exception $e){
            \think\facade\Db::rollback();
            throw new \Exception($e->getMessage());
        }
        if($model['mch_id']){
            MerchantMoneyLogsModel::recordData(0,$model['mch_id'],-$money,"提现",[
                'm_type'=>1,
                'q_money'=>$user_model['money'],
                'h_money'=>$user_model['money']-$money,
            ]);
        }else{
            UserLogsModel::recordData(2,$user_model['id'],-$money,"提现",[
                'm_type'=>1,
                'q_money'=>$user_model['money'],
                'h_money'=>$user_model['money']-$money,
            ]);
        }


    }

    //获取提现金额
    public static function getSumMoney(UserModel $user_model=null,$type='')
    {
        if(empty($user_model)){
            return '0.00';
        }
        $where= [];
        $where[] = ['uid','=',$user_model['id']];
        if($type=='get'){
            $where[] = ['status','=',1];
        }elseif($type='wait'){
            $where[] = ['status','=',0];
        }
        return self::where($where)->sum('money');

    }

    public static function cancel(BaseModel $user_model ,array $input_data = [])
    {
        $_lang = $input_data['_lang']??'';
        $id = $input_data['id']??0;
        if(empty($id)) throw new \Exception(LangMap::getStr('error_params',$_lang).":id");
        $model = self::find($id);
        if(empty($model)) throw new \Exception(LangMap::getStr('error_data',$_lang));
        if($user_model instanceof UserModel){
            if($model['uid']!=$user_model['id']) throw new \Exception( LangMap::getStr('error_opt_no_auth',$_lang) );
        }else{
            $user_model = UserModel::find($model['uid']);
        }
//        $handle_action = $model->getHandleAction(app()->http->getName()==='admin'?'m_handle':'u_handle');
        if(!empty($model['status'])) throw new \Exception(LangMap::getStr('error_draw_opt_state_cancel',$_lang));
        //创建记录
        try{
            \think\facade\Db::startTrans();
            $row_num = UserModel::where(['uid'=>$model['uid']])->update([
                'money' => \think\facade\Db::raw('money+'.$model['money']),
            ]);
            if(!$row_num) throw new \Exception(LangMap::getStr('error_try_later',$_lang) );
            $model->setAttrs([
                'cancel_time'=>date('Y-m-d H:i:s'),
                'status'=>3,
            ]);
            $model->save();

            \think\facade\Db::commit();
        }catch (\Exception $e){
            \think\facade\Db::rollback();
            throw new \Exception($e->getMessage());
        }

        UserLogsModel::recordData(0,$model['uid'],$model['money'],LangMap::getStr('error_withdraw_cancel','en'),[
            'intro_ban'=>LangMap::getStr('error_withdraw_cancel','ban'),
            'm_type'=>1,
            'q_money'=>$user_model['money'],
            'h_money'=>$user_model['money']+$model['money'],
        ]);
    }

    public static function auth(array $input_data = [])
    {
        $id = $input_data['id']??0;
        $auth_state = empty($input_data['auth_state'])?2:$input_data['auth_state'];
        $auth_content = trim(empty($input_data['auth_content'])?'':$input_data['auth_content']);
        if(empty($id)) throw new \Exception('参数异常：id');
        $model = self::find($id);
        if(empty($model)) throw new \Exception('对象不存在');
        if(!empty($model['mch_id'])){
            $mch_model = MerchantModel::find($model['mch_id']);
        }else{
            $user_model = UserModel::find($model['uid']);
        }
        //创建记录
        $log_content = "";
        try{
            \think\facade\Db::startTrans();
            if($auth_state==1){ //通过
                $log_content = "提现通过审核";
            }else{
                $log_content = "提现审核被拒";
                if(!empty($model['mch_id'])){
                    $row_num = MerchantModel::where(['id'=>$model['mch_id']])->update([
                        'money' => \think\facade\Db::raw('money+'.$model['money']),
                    ]);
                }else{
                    $row_num = UserModel::where(['id'=>$model['uid']])->update([
                        'money' => \think\facade\Db::raw('money+'.$model['money']),
                    ]);
                }

                if(!$row_num) throw new \Exception('操作频繁,请重新尝试');
            }

            $model->setAttrs([
                'auth_content'=>$auth_content,
                'auth_time'=>date('Y-m-d H:i:s'),
                'auth_state' => $auth_state,
                'status'=>$auth_state,
            ]);
            $model->save();
            \think\facade\Db::commit();
        }catch (\Exception $e){
            \think\facade\Db::rollback();
            throw new \Exception($e->getMessage());
        }
        if($auth_state!=1){
            if(!empty($model['mch_id'])){
                MerchantMoneyLogsModel::recordData(0,$model['uid'],$model['money'],$log_content,[
                    'm_type'=>1,
                    'q_money'=>$mch_model['money'],
                    'h_money'=>$mch_model['money']+$model['money'],
                ]);
            }else{
                UserLogsModel::recordData(2,$model['uid'],$model['money'],$log_content,[
                    'm_type'=>1,
                    'q_money'=>$user_model['money'],
                    'h_money'=>$user_model['money']+$model['money'],
                ]);
            }


        }
    }


    public function apiFullInfo()
    {
        $linkUser = $this->getRelation('linkUser');

        return array_merge($this->apiNormalInfo(),[
            "auth_state"=>(int)$this['auth_state'],
            "auth_time"=>(string)$this['auth_time'],
            "auth_content"=>(string)$this['auth_content'],

            'user_id' => (int)$linkUser['id'],
            'user_name' => (string)$linkUser['nickname'],
            'user_avatar' => (string)$linkUser['avatar'],
            'user_mobile' => (string)$linkUser['mobile'],
        ]);
    }

    public function apiNormalInfo()
    {
        return [
            'id' => $this['id'],
            'type' => $this['type'],
            "q_money"=>$this['q_money'],
            "money"=>$this['money'],
            "h_money"=>$this['q_money']-$this['money'],
            "per"=>$this['per'],
            "service_fee"=>$this['service_fee'],
            "pay_money"=>$this['pay_money'],
            "check_time"=>$this['check_time'],
            "pay_time"=>$this['pay_time'],
            "refuse_time"=>$this['refuse_time'],
            "account_name"=>$this['account_name'],
            "account"=>$this['account'],
            "remark"=>$this['remark'],
            "withdraw_info"=>$this['withdraw_info'],


            "create_time"=>$this['create_time'],
            "cancel_time"=>$this['cancel_time'],

            "handle_time"=>(string)$this['auth_time'],
            'status'=> (int)$this['status'],
            'status_name' => self::getPropInfo('fields_status',$this['status'],'name'),

        ];
    }

    public function linkUser()
    {
        return $this->belongsTo(UserModel::class,'uid');
    }

}